from grid_env_ideal_obs_repeat_task import *
from grid_agent import *
from checkpoint_utils import *
from maze_factory import *
from replay_config import *
import argparse
import json
import sys
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib.lines import Line2D
from sklearn.manifold import TSNE
import random
from sklearn.decomposition import PCA
from matplotlib.animation import FuncAnimation
from sklearn.cluster import KMeans
import threading
import mplcursors
from mpl_toolkits.mplot3d.art3d import Poly3DCollection

def progress_bar(current, total, barLength = 100):
    percent = float(current) * 100 / total
    arrow = '-' * int(percent/100 * barLength - 1) + '>'
    spaces = ' ' * (barLength - len(arrow))

    print('Progress: [%s%s] %d %%' % (arrow, spaces, percent), end='\r')
    sys.stdout.flush()

@partial(jax.jit, static_argnums=(3,))
def model_forward(variables, state, x, model):
    """ forward pass of the model
    """
    return model.apply(variables, state, x)

@jit
def get_action(y):
    return jnp.argmax(y)
get_action_vmap = jax.vmap(get_action)

# load landscape and states from file
def load_task(pth = "./logs/task.json", display = True):
    # open json file
    with open(pth, "r") as f:
        data = json.load(f)
        landscape = data["data"]
        state = data["state"]
        goal = data["goal"]
        if display:
            print("state: ", state)
            print("goal: ", goal)
            print("landscape: ", landscape)
    return landscape, state, goal


def get_intrinsic_pc():

    """ parse arguments
    """
    rpl_config = ReplayConfig()

    parser = argparse.ArgumentParser()
    parser.add_argument("--model_pth", type=str, default=rpl_config.model_pth)
    parser.add_argument("--map_size", type=int, default=rpl_config.map_size)
    parser.add_argument("--task_pth", type=str, default=rpl_config.task_pth)
    parser.add_argument("--log_pth", type=str, default=rpl_config.log_pth)
    parser.add_argument("--nn_size", type=int, default=rpl_config.nn_size)
    parser.add_argument("--nn_type", type=str, default=rpl_config.nn_type)
    parser.add_argument("--show_kf", type=str, default=rpl_config.show_kf)
    parser.add_argument("--visualization", type=str, default=rpl_config.visualization)
    parser.add_argument("--video_output", type=str, default=rpl_config.video_output)
    parser.add_argument("--life_duration", type=int, default=rpl_config.life_duration)
    parser.add_argument("--start_i", type=int, default=rpl_config.start_i)
    parser.add_argument("--end_i", type=int, default=rpl_config.end_i)

    args = parser.parse_args()

    rpl_config.model_pth = args.model_pth
    rpl_config.map_size = args.map_size
    rpl_config.task_pth = args.task_pth
    rpl_config.log_pth = args.log_pth
    rpl_config.nn_size = args.nn_size
    rpl_config.nn_type = args.nn_type
    rpl_config.show_kf = args.show_kf
    rpl_config.visualization = args.visualization
    rpl_config.video_output = args.video_output
    rpl_config.life_duration = args.life_duration
    rpl_config.start_i = args.start_i
    rpl_config.end_i = args.end_i

    """ load model
    """
    params = load_weights(rpl_config.model_pth)

    # get elements of params
    tree_leaves = jax.tree_util.tree_leaves(params)
    for i in range(len(tree_leaves)):
        print("shape of leaf ", i, ": ", tree_leaves[i].shape)
    
    """ create agent
    """
    if rpl_config.nn_type == "vanilla":
        model = RNN(hidden_dims = rpl_config.nn_size)
    elif rpl_config.nn_type == "gru":
        model = GRU(hidden_dims = rpl_config.nn_size)

    # check if param fits the agent
    if rpl_config.nn_type == "vanilla":
        assert params["params"]["Dense_0"]["kernel"].shape[0] == rpl_config.nn_size + 10

    n_samples = 1000
    k1 = npr.randint(0, 1000000)
    rnn_state = model.initial_state_rnd(n_samples, k1)
    rnn_state_old = rnn_state.copy()
    diff = jnp.abs(rnn_state - rnn_state_old)
    rnn_state_old = rnn_state.copy()
    diff_norm = jnp.linalg.norm(diff, axis=1)
    diff_norm_old = diff_norm.copy()
    norm_std = diff_norm.copy()

    rnn_state_init = rnn_state.copy()

    obs_zero = jnp.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for i in range(n_samples)])

    rnn_state_trajectory = []

    for t in range(rpl_config.life_duration):

        if t == rpl_config.probe_point:
            rnn_state_init = rnn_state.copy()

        progress_bar(t, rpl_config.life_duration)

        """ model forward 
        """
        rnn_state, y1 = model_forward(params, rnn_state, obs_zero, model)
        diff = jnp.abs(rnn_state - rnn_state_old)
        rnn_state_old = rnn_state.copy()
        diff_norm = jnp.linalg.norm(diff, axis=1)
        norm_std = 0.4 * jnp.abs(diff_norm - diff_norm_old) + 0.6 * norm_std
        diff_norm_old = diff_norm.copy()

        rnn_state_trajectory.append(np.array(rnn_state).copy())
            
    print(rnn_state.shape)
    print(norm_std.shape)
    rnn_state_np = np.array(rnn_state)

    # 将 rnn_state_trajectory 展开成 rnn_state_np 的形状
    rnn_state_trajectory_np = np.array(rnn_state_trajectory)
    rnn_state_trajectory_np = rnn_state_trajectory_np.reshape(-1, rnn_state_trajectory_np.shape[-1])
    print("shape of rnn_state_trajectory_np: ", rnn_state_trajectory_np.shape)

    # 对 rnn_state_np 进行 PCA
    pca = PCA()
    # pca.fit(rnn_state_np)
    pca.fit(rnn_state_trajectory_np)

    # 打印 variance ratio
    print(pca.explained_variance_ratio_)

    rnn_state_np_pca = pca.transform(rnn_state_np)

    # 创建KMeans对象，指定聚类数为4
    kmeans = KMeans(n_clusters=4)
    # 对rnn_state_np_pca进行聚类
    kmeans.fit(rnn_state_np_pca)
    # 获取聚类中心的坐标
    cluster_centers = kmeans.cluster_centers_

    return pca, cluster_centers


def main():
    
    seq_len = 15
    
    n_samples = 1000

    """ parse arguments
    """
    rpl_config = ReplayConfig()

    parser = argparse.ArgumentParser()
    parser.add_argument("--model_pth", type=str, default=rpl_config.model_pth)
    parser.add_argument("--map_size", type=int, default=rpl_config.map_size)
    parser.add_argument("--task_pth", type=str, default=rpl_config.task_pth)
    parser.add_argument("--log_pth", type=str, default=rpl_config.log_pth)
    parser.add_argument("--nn_size", type=int, default=rpl_config.nn_size)
    parser.add_argument("--nn_type", type=str, default=rpl_config.nn_type)
    parser.add_argument("--show_kf", type=str, default=rpl_config.show_kf)
    parser.add_argument("--visualization", type=str, default=rpl_config.visualization)
    parser.add_argument("--video_output", type=str, default=rpl_config.video_output)
    parser.add_argument("--life_duration", type=int, default=rpl_config.life_duration)

    args = parser.parse_args()

    rpl_config.model_pth = args.model_pth
    rpl_config.map_size = args.map_size
    rpl_config.task_pth = args.task_pth
    rpl_config.log_pth = args.log_pth
    rpl_config.nn_size = args.nn_size
    rpl_config.nn_type = args.nn_type
    rpl_config.show_kf = args.show_kf
    rpl_config.visualization = args.visualization
    rpl_config.video_output = args.video_output
    rpl_config.life_duration = args.life_duration

    """ load model
    """
    params = load_weights(rpl_config.model_pth)
    
    arrow_length = 1
    arrow_list = np.array([[arrow_length, 0], [-arrow_length, 0], [0, arrow_length], [0, -arrow_length], [0, 0]])

    nn_type = ''
    if rpl_config.nn_type == "vanilla":
        nn_type = "vanilla"
    elif rpl_config.nn_type == "gru":
        nn_type = "gru"

    # 生成一个二进制串集合，其中每个元素都是一个长度为8的二进制串，要求这些二进制串从 000000000 遍历到 111111111
    binary_set = set()
    for i in range(256):
        binary_string = format(i, '08b')
        binary_set.add(binary_string)
    # 将 binary_set 中的 11111111 元素删除
    binary_set.remove("11111111")
    # 将 binary_set 中所有格式为 "x1x1x1x1" 的元素删除
    binary_set_bk = binary_set.copy()
    for binary in binary_set_bk:
        if binary[1] == '1' and binary[3] == '1' and binary[4] == '1' and binary[6] == '1':
            binary_set.remove(binary)
    print("binary_set: ", binary_set)
    
    # 对 binary_set 进行排序，使得其中的元素从 00000000 遍历到 11111110
    binary_list = sorted(binary_set)
    # 将 binary_list 中的每个元素进行这样的操作：在中间插入一个0，例如 "00000000" 转换为 "000000000"；然后在结尾处插入一个0，例如 "000000000" 转换为 "0000000000"
    binary_list = [i[:4] + "0" + i[4:] + "0" for i in binary_list]
    # 将 binary_list 中的元素转换为整数数组，例如 "00000000" 转换为 [0, 0, 0, 0, 0, 0, 0, 0]
    binary_list = [list(map(int, list(i))) for i in binary_list]
    binary_list = np.array(binary_list)
    print("shape of binary_list: ", binary_list.shape)

    binary_list, arrow_list = np.array(binary_list), np.array(arrow_list)

    def make_obs_img(obs_int):
        # 将形状为 (10,) 的 obs 裁减掉最后一位，变成形状为 (9,) 的 obs
        obs = obs_int[:-1]
        # 将 obs 转换为形状为 (3, 3) 的 numpy 数组
        obs = obs.reshape((3, 3))
        
        # 将 obs 中的 1 替换为 255
        obs = (1-obs) * 255
        # 将 obs 转换为形状为 (3, 3, 1) 的 numpy 数组
        obs = obs.reshape((3, 3, 1))
        # 将 obs 转换为形状为 (3, 3, 3) 的 numpy 数组
        obs = np.concatenate((obs, obs, obs), axis=2)
        # 将 obs 转换为 opencv 的8比特图像格式
        obs = obs.astype(np.uint8)
        # 将 obs 转换为形状为 (60, 60, 3) 的 numpy 数组
        obs = cv2.resize(obs, (60, 60), interpolation=cv2.INTER_NEAREST)
        # 在 obs 上绘制 3x3 的灰色网格
        for i in range(1, 3):
            cv2.line(obs, (0, i*20), (60, i*20), (100, 100, 100), 1)
            cv2.line(obs, (i*20, 0), (i*20, 60), (100, 100, 100), 1)
        # 在 obs 的边缘绘制灰色边框
        cv2.rectangle(obs, (0, 0), (59, 59), (100, 100, 100), 1)
        return obs

    # get elements of params
    tree_leaves = jax.tree_util.tree_leaves(params)
    for i in range(len(tree_leaves)):
        print("shape of leaf ", i, ": ", tree_leaves[i].shape)
    
    """ load task trajectories
    """
    slice_fn = "_" + nn_type + "_" + str(seq_len)
    # tracelet_slices = np.load("./logs/tracelet_slices"+slice_fn+".npy")
    # obs_slices = np.load("./logs/obs_slices"+slice_fn+".npy")
    # action_slices = np.load("./logs/action_slices"+slice_fn+".npy")
    trajectories = np.load("./logs/tracelet_slices"+slice_fn+".npy")
    obs_record = np.load("./logs/obs_slices"+slice_fn+".npy")
    action_slices = np.load("./logs/action_slices"+slice_fn+".npy")

    print("shape of trajectories: ", trajectories.shape)
    print("shape of obs_record: ", obs_record.shape)
    print("shape of action_slices: ", action_slices.shape)

    """ 分割最终的循环路径
    """
    # 定义最终轨迹为：一条轨迹中最后一次 goal（包含） 到前一次 goal的下一步（包含）之间的轨迹
    # 将所有 qc_pass 的最终轨迹提取出来
    trajectories_final_qc_pass = trajectories.tolist()
    obs_seq_final_qc_pass = obs_record.tolist()
    
        # 将 obs_seq_final_qc_pass 中的每一个元素转化为其在 binary_list 列表中对应元素的编号
    obs_seq_final_qc_pass_binary = []
    for obs_seq in obs_seq_final_qc_pass:
        obs_seq_binary = []
        for obs in obs_seq:
            # 查找 obs 在 binary_list 中的序号
            index_ = np.argwhere(np.all(obs == binary_list, axis=1))
            obs_seq_binary.append(index_[0][0])
        obs_seq_final_qc_pass_binary.append(obs_seq_binary)

    # 测试
    rnd_index = np.random.randint(0, len(trajectories_final_qc_pass))

    # rnd_index = 113

    print("rnd_index: ", rnd_index)
    
    """ action list
    """
    action_list = jnp.array([[0, 1], [0, -1], [1, 0], [-1, 0], [0, 0]])

    """ step physics
    """
    @partial(jax.jit)
    def step_physics_one_grid(position, action, action_list):
        position_next = position + action_list[action]
        return position_next
    step_physics_one_grid_vmap = jax.vmap(step_physics_one_grid, in_axes=(0, 0, None))
    
    """ create agent
    """
    if rpl_config.nn_type == "vanilla":
        model = RNN(hidden_dims = rpl_config.nn_size)
    elif rpl_config.nn_type == "gru":
        model = GRU(hidden_dims = rpl_config.nn_size)

    best_fit_initial_state = 0
    min_diff = 10000
    minimum_index = 0

    for k in range(3):

        k1 = npr.randint(0, 1000000)
        rnn_state = model.initial_state_rnd(n_samples, k1)

        rnn_state_initial = rnn_state.copy()

        obs_zero = jnp.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for i in range(n_samples)])

        rnn_state_trajectory = []
        actions_trajectory = []

        random_integers = obs_seq_final_qc_pass_binary[rnd_index]

        random_integers_i = 0
        def update_random_integers_i():
            nonlocal random_integers_i
            nonlocal seq_len
            random_integers_i += 1
            random_integers_i %= seq_len
        
        tracelets = []
        tracelet = []
        actionlets = []
        actionlet = []

        """ run forced dynamics
        """
        for t in range(rpl_config.life_duration):

            if t == rpl_config.probe_point:
                rnn_state_init = rnn_state.copy()

            progress_bar(t, rpl_config.life_duration)

            tracelet.append(np.array(rnn_state).copy())
            if random_integers_i == seq_len-1:
                tracelets.append(tracelet.copy())
                tracelet.clear()

            random_obs = binary_list[random_integers[random_integers_i]]
            obs_zero = jnp.array([random_obs for i in range(n_samples)])

            """ model forward 
            """
            rnn_state, y1 = model_forward(params, rnn_state, obs_zero, model)
            actions = get_action_vmap(y1)

            rnn_state_trajectory.append(np.array(rnn_state).copy())
            actions_trajectory.append(np.array(actions).copy())
            update_random_integers_i()

            actionlet.append(actions.copy())
            if random_integers_i == seq_len-1:
                actionlets.append(actionlet.copy())
                actionlet.clear()

        actionlets = actionlets[1:-2]
        actionlets = np.array(actionlets)
        # 将 actionlets 的第2维和第3维交换
        actionlets = np.swapaxes(actionlets, 1, 2)
        print("shape of actionlets: ", actionlets.shape)

        actionlets_limit_cycle = actionlets[-2]
        print("shape of actionlets: ", actionlets_limit_cycle.shape)

        """ 逐个检测 action 序列和原始数据的相似度
        """
        action_slice = action_slices[rnd_index]
        diff = []

        # # 将 action_slice 向前滚动一位
        # action_slice = np.roll(action_slice, -1, axis=0)

        for i in range(actionlets_limit_cycle.shape[0]):
            actionlet = actionlets_limit_cycle[i]

            # 计算 actionlet 和 action_slice 中不同元素的个数
            diff_n_elements = np.sum(actionlet != action_slice)

            diff.append(diff_n_elements)
        diff = np.array(diff)
        print("min diff: ", np.min(diff))
        
        if min_diff > np.min(diff):
            min_diff = np.min(diff)
            minimum_index = np.argmin(diff)
            best_fit_initial_state = rnn_state_initial[minimum_index].copy()

        if min_diff <= 2.0:
            break

    """ run selected forced dynamics for position_bins
    """
    random_integers_i = 0
    rnn_state = jnp.array([best_fit_initial_state])
    n_samples_selected = 1
    bin_size = 25
    position_bins = np.zeros((bin_size, bin_size))
    center_shift = 11
    # position integrators
    position_integrators = jnp.zeros((n_samples_selected, 2))

    def reset_position_integrators():
        nonlocal position_integrators
        position_integrators = jnp.zeros((n_samples_selected, 2))

    for t in range(rpl_config.life_duration):
        progress_bar(t, rpl_config.life_duration)

        # update position_bins
        position_integrators_bins = position_integrators + center_shift
        # 将 position_integrators_bins 转换为整数类型的数组
        position_integrators_bins = position_integrators_bins.astype(int)
        position_integrators_bins = np.clip(position_integrators_bins, None, bin_size-1)

        if t >= rpl_config.life_duration - 2*seq_len:
            # 使用 np.add.at 函数进行累加操作
            np.add.at(position_bins, tuple(position_integrators_bins.T), 1)
            
        random_obs = binary_list[random_integers[random_integers_i]]
        obs_zero = jnp.array([random_obs for i in range(n_samples_selected)])
        """ model forward 
        """
        rnn_state, y1 = model_forward(params, rnn_state, obs_zero, model)
        actions = get_action_vmap(y1)
        # integrate positions
        if random_integers_i == 0:
            reset_position_integrators()
        position_integrators = step_physics_one_grid_vmap(position_integrators, actions, action_list)
        update_random_integers_i()

    position_bins = position_bins.T

    x = np.array(trajectories_final_qc_pass[rnd_index])[:,0]
    y = np.array(trajectories_final_qc_pass[rnd_index])[:,1]

    # 创建一个新的图形窗口，并设置图形的大小
    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 12))

    # 在第一个子图中绘制散点图和连线
    ax1.scatter(x, y, s=80)
    for i, (xi, yi) in enumerate(zip(x, y)):
        ax1.text(xi, yi, str(i), ha='left', va='bottom', fontsize=20)
    ax1.plot(x, y, '-')
    ax1.set_xlim(0, 11)
    ax1.set_ylim(0, 11)
    ax1.set_title('Scatter Plot of Coordinates')
    ax1.set_xlabel('X')
    ax1.set_ylabel('Y')

    # 在第二个子图中绘制热度图
    ax2.imshow(position_bins, cmap='hot', origin='lower')
    ax2.plot(x-x[0]+center_shift, y-y[0]+center_shift, '-')
    ax2.set_title('Heatmap of position_bins')
    ax2.set_xlabel('X')
    ax2.set_ylabel('Y')

    # 调整子图之间的间距
    plt.tight_layout()

    # 显示图形
    plt.show()
    

if __name__ == "__main__":
    main()